/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.classifyQuestion;

import javax.inject.Inject;

import org.apache.commons.lang3.Validate;

import ru.irenproject.AbstractQuestionEditor;
import ru.irenproject.Action;
import ru.irenproject.Check;
import ru.irenproject.Question;
import ru.irenproject.TestInputException;
import ru.irenproject.classifyQuestion.ClassifyQuestionProtos.ClassifyQuestionEditorShape;
import ru.irenproject.pad.PadEditor;
import ru.irenproject.store.Event;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Thing;

import com.google.protobuf.Message;

public final class ClassifyQuestionEditor extends AbstractQuestionEditor {
  public static final class AddItemInput {
    public int categoryIndex;
  }

  public static final class DeleteCategoryInput {
    public int index;
  }

  public static final class DeleteItemInput {
    public int categoryIndex;
    public int itemIndex;
  }

  public static final class MoveCategoryInput {
    public int index;
    public boolean forward;
  }

  public static final class MoveItemInput {
    public int categoryIndex;
    public int itemIndex;
    public boolean forward;
  }

  public static final class SetOptionsInput {
    public Integer itemLimit;
    public Integer minItemsPerCategory;
  }

  @Stash private ClassifyQuestionProtos.ClassifyQuestionEditor.Builder $;

  @Inject ClassifyQuestionEditor() {}

  @Override public ClassifyQuestion question() {
    return get($.getQuestion(), ClassifyQuestion.class);
  }

  @Override protected void setQuestion(Question question) {
    Validate.isInstanceOf(ClassifyQuestion.class, question);

    $.setQuestion(question.id());
    $.setFormulationEditor(PadEditor.create(question().formulation()).id());
    syncEditors();
    question().addListener(this);
  }

  private void syncEditors() {
    $.clearElement();
    int categoryCount = question().categoryCount();
    for (int i = 0; i < categoryCount; ++i) {
      $.addElementBuilder()
          .setCategoryIndex(i)
          .setEditor(PadEditor.open(question().getCategoryTitle(i)).id())
          .setCanMoveUp(i > 0)
          .setCanMoveDown(i < categoryCount - 1);
      int itemCount = question().getItemCount(i);
      for (int j = 0; j < itemCount; ++j) {
        $.addElementBuilder()
            .setCategoryIndex(i)
            .setItemIndex(j)
            .setEditor(PadEditor.open(question().getItem(i, j)).id())
            .setCanMoveUp((j > 0) || (i > 0))
            .setCanMoveDown((j < itemCount - 1) || (i < categoryCount - 1));
      }
    }
  }

  @Override protected void handleEvent(Event e, Thing source) {
    if (e instanceof ClassifyQuestion.ChangeEvent) {
      syncEditors();
      markForRender();
    }
  }

  @Override public Message render() {
    ClassifyQuestion q = question();
    ClassifyQuestionEditorShape.Builder b = ClassifyQuestionEditorShape.newBuilder()
        .setFormulationEditor($.getFormulationEditor())
        .addAllElement($.getElementList())
        .setCanAddCategory(q.categoryCount() < ClassifyQuestion.MAX_CATEGORIES)
        .setCanAddItem(q.totalItemCount() < ClassifyQuestion.MAX_ITEMS)
        .setHasDefaultOptions(q.hasDefaultOptions())
        .setMaxItems(ClassifyQuestion.MAX_ITEMS);
    if (q.hasItemLimit()) {
      b.setItemLimit(q.itemLimit());
      b.setMinItemsPerCategory(q.minItemsPerCategory());
    }
    return b.build();
  }

  @Action(badInput = TestInputException.class)
  public void doAddCategory() {
    question().addCategory();
  }

  @Action(badInput = TestInputException.class)
  public void doAddItem(AddItemInput in) {
    question().addItem(in.categoryIndex);
  }

  @Action(badInput = TestInputException.class)
  public void doDeleteCategory(DeleteCategoryInput in) {
    question().deleteCategory(in.index);
  }

  @Action(badInput = TestInputException.class)
  public void doDeleteItem(DeleteItemInput in) {
    question().deleteItem(in.categoryIndex, in.itemIndex);
  }

  @Action(badInput = TestInputException.class)
  public void doMoveCategory(MoveCategoryInput in) {
    question().moveCategory(in.index, in.forward);
  }

  @Action(badInput = TestInputException.class)
  public void doMoveItem(MoveItemInput in) {
    question().moveItem(in.categoryIndex, in.itemIndex, in.forward);
  }

  @Action(badInput = TestInputException.class)
  public void doSetOptions(SetOptionsInput in) {
    if (in.itemLimit == null) {
      question().clearItemLimit();
    } else {
      question().setItemLimit(in.itemLimit);
      question().setMinItemsPerCategory(Check.inputNotNull(in.minItemsPerCategory));
    }
  }
}
